import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import eventEmitter from '@/utils/eventEmitter';
export const aboutRoute = {
  path: '/about',
  name: 'about',
  component: () => import('@/views/about/index.vue'),
  meta: {},
  children: []
} as RouteRecordRaw;

// import.meta.glob 为 vite 提供的特殊导入方式
// 它可以将模块中全部内容导入并返回一个Record对象
// 默认为懒加载模式 加入配置项 eager 取消懒加载
const modules: Record<string, any> = import.meta.glob('./modules/*.ts', {
  eager: true
});

const routes: Array<RouteRecordRaw> = Object.keys(modules).map(key => modules[key].default);

const router = createRouter({
  history: createWebHistory(),
  routes: [aboutRoute, ...routes]
});

const hasTokenBlacklist: Array<string> = ['/login', '/register']; // 登录后不可访问的页面
const noTokenWhitelist: Array<string> = ['/login', '/register', '/about', '/404', '/403']; // 未登录可访问的页面

router.beforeEach((to, _from, next) => {
  const isToken: boolean = !!sessionStorage.getItem('userInfo'); // 判断是否登录
  NProgress.start();
  if (isToken) {
    if (hasTokenBlacklist.includes(to.path)) {
      eventEmitter.emit('ROUTER:CANCEL_PENDING'); // 取消上个页面的请求
      next('/');
    } else {
      eventEmitter.emit('ROUTER:CANCEL_PENDING'); // 取消上个页面的请求
      next();
    }
  } else if (noTokenWhitelist.includes(to.path)) {
    eventEmitter.emit('ROUTER:CANCEL_PENDING'); // 取消上个页面的请求
    next();
  } else {
    eventEmitter.emit('ROUTER:CANCEL_PENDING'); // 取消上个页面的请求
    next('/login');
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
